
package com.azt.front.action.enquiry;

import com.alibaba.fastjson.JSONArray;
import com.azt.api.dto.*;
import com.azt.api.enums.EnqEnquiryEnum;
import com.azt.api.enums.EnqPaymentEnum;
import com.azt.api.enums.EnqQuoteEnum;
import com.azt.api.enums.UserEnum;
import com.azt.api.pojo.*;
import com.azt.api.service.*;
import com.azt.front.action.enquiry.model.EnqBgetPchaseSaveWrap;
import com.azt.front.action.enquiry.model.EnqRecommendChoose;
import com.azt.front.permission.RequireCompany;
import com.azt.front.permission.RequireProvider;
import com.azt.front.permission.RequirePurchase;
import com.azt.front.permission.RequireUser;
import com.azt.front.utils.ContextUtil;
import com.azt.model.AjaxJson;
import com.azt.model.page.TPagination;
import com.azt.provider.CategoryConstants;
import com.azt.utils.*;
import com.xiaoleilu.hutool.util.StrUtil;
import freemarker.template.TemplateModel;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.support.SessionStatus;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.*;
import java.util.zip.ZipOutputStream;

import static com.azt.front.utils.Globals.PAGESIZE;

/**
 * 寻价报价
 * Created by 张栋 on 2016/9/1811:06
 */
@Controller
@RequestMapping("/enquiry")
@SessionAttributes(value = {"enqmodel", "recod","CPModel"})
public class EnquiryAction {

    @Autowired
    private EnqQuoteService quoteService;
    @Autowired
    private EnquiryActionExt ext;

    @Autowired
    private EnqEnquiryService enq;

    @Autowired
    private EnqQuoteService eqs;

    @Autowired
    private CompanyService companyService;

    @Autowired
    private UserPermissionService userPermissionService;

    @Autowired
    private UserService userService;


    @Autowired
    private EnqEnquiryAnalysisService  analysisService;


    @Autowired
    private ProCategoryService proCategoryService;

    /*预算询价*/
    public static final Integer QTYPE_DESIGN = 1;
    /*采购询价*/
    public static final Integer QTYPE_PURCHASE = 2;

    @InitBinder
    protected void initBinder(WebDataBinder binder) {
        binder.setAutoGrowCollectionLimit(5000);
    }

    /**
     * 询价我的项目列表
     * <p>
     * 同一个公司下面的人都可以看的到,所以根据 company去查
     * Created by 张栋 on 2016/9/18 11:28
     */
    @RequireCompany(state = Company.AUDIT_STATE_PASS)
    @RequestMapping("/project/list")
    @RequirePurchase
    public String projectList(ModelMap model, Integer pageNo, EnqProjSearchDto dto) {

        User user = ContextUtil.getUser();
        Integer companyId = user.getCompanyId();
        Integer userId = user.getId();


        dto.setCustomerId(companyId);
        dto.setUserId(userId);


        TPagination<EnqProjListDto> myProject = null;
        myProject = enq.getMyProject(pageNo, PAGESIZE, dto);


        model.put("projects", myProject);

        Map<String, Object> searchMap = BeanUtils.copyBean2Map(dto);
        myProject.setParams(searchMap);


        //分公司
        boolean hasPermission = enq.isAdminOrFinance(dto.getUserId());
        List<Integer> companyids = new ArrayList<>();
        companyids.add(dto.getCustomerId());
        if(hasPermission){//如果有权限,则查总公司与子公司的
            //获取公司下的所有子公司
            List<Company> companies = companyService.allBranchCompany(dto.getCustomerId());
            if(companies!=null && !companies.isEmpty()){
                Company mycompany = companyService.getCompanyById(companyId);
                companies.add(0,mycompany);
                model.put("companies",companies);
            }
        }


        return "enquiry/enquiry_project_list";
    }


    /**
     * 判断创建的项目名,是不是已经存在, 在我创建的项目里
     * Created by 张栋 on 2017/1/16 10:25
     */
    @RequestMapping("/project/ismy")
    @ResponseBody
    public AjaxJson ismy(String projectname) {
        AjaxJson j = new AjaxJson();
        User user = ContextUtil.getUser();
        if (user == null) return j;
        projectname = projectname.trim();
        if (StringUtils.isNotBlank(projectname)) {
            List<EnqProject> projects = enq.getEnqProjectByName(projectname, user.getId());
            if (projects != null && !projects.isEmpty()) {
                j.setSuccess(false);
                j.setMsg("项目名称已经存在,请选择已有项目");
            }
        }
        return j;
    }

    /**
     * 关闭项目
     * Created by 张栋 on 2016/11/14 10:20
     */
    @RequireCompany(state = Company.AUDIT_STATE_PASS)
    @RequestMapping("/project/close")
    @ResponseBody
    public AjaxJson closeProject(Integer projectId) {
        AjaxJson j = new AjaxJson();
        boolean isok = enq.closeProject(projectId);
        if (isok) {
            j.setSuccess(true);
        } else {
            j.setSuccess(false);
            j.setMsg("已经有订单的项目不能关闭");
        }
        return j;
    }

    /**
     * 关闭询价
     * Created by 张栋 on 2016/11/21 13:26
     */
    @RequireCompany(state = Company.AUDIT_STATE_PASS)
    @RequestMapping("/close")
    @ResponseBody
    public AjaxJson closeEnquiry(Integer enqid) {
        AjaxJson j = new AjaxJson();
        boolean isok = enq.closeEnquiry(enqid);
        if (!isok) {
            j.setSuccess(false);
            j.setMsg("有订单的询价不能关闭");
        }
        return j;
    }


    /**
     * 项目详情
     * 设计/采购/预算  列表
     * 采购/预算  只能看到自己的
     * 设计   全公司可以看
     *
     * @param qtype      '1.设计需求 2.采购询价',  3临时的,代表预算
     * @param budgettype 预算类型 -1 所有
     *                   Created by 张栋 on 2016/9/19 10:09
     *                   有预算询价的
     *                   http://front.azt.com:8091/enquiry/project/detail/p/945/t/1
     */
    @RequireCompany(state = Company.AUDIT_STATE_PASS)
    @RequirePurchase
    @RequestMapping("/project/detail/p/{projid}/t/{qtype}")
    public String projectDetail(ModelMap model, @PathVariable("projid") Integer projid, @PathVariable("qtype") Integer qtype, Integer budgettype, Integer pageNo) {
        EnqProjectExt projectExt = enq.getEnqProjectExtById(projid);
        model.put("project", projectExt);
        User user = ContextUtil.getUser();
        Integer companyId = user.getCompanyId();
        Integer userid = user.getId();
        model.put("userid", userid);
        pageNo = pageNo == null ? 1 : pageNo;
        if (qtype < 3) {
            //管理/财务 ,  可以看到自己公司与分公司下的询价 ,普通只能看到自己的询价.
            //规则变动: 2017.3.14, 杨程  可以看到该项目下的所有询价等, 但自己只能操作自己的
            TemplateModel staticModel = FreemarkerUtils.getStaticModel(EnqEnquiryEnum.class);
            model.put("EnqEnquiryEnum", staticModel);
            //详情,采购/设计 列表
            TPagination<EnqProjDetailDto> pag = enq.getEnqProjDetail(projid, qtype, userid, companyId, pageNo, PAGESIZE);
            model.put("pagination", pag);


        } else {

            //管理/财务 ,  可以看到自己公司与分公司下的预算 ,普通的可以看到当前公司下的预算
            budgettype = budgettype == null ? -1 : budgettype;
            TPagination<EnqBudget> budGetDetail = enq.getBudGetDetail(projid, budgettype, userid, companyId, pageNo, PAGESIZE);
            budGetDetail.setParam("budgettype", budgettype + "");
            model.put("pagination", budGetDetail);
        }

        return "enquiry/enquiry_project_detail_" + qtype;
    }


    /**
     * 项目详情,采购询价,查看询价
     * 采购询价审核结果-公开.html
     * Created by 张栋 on 2016/10/9 13:29
     */
    @RequireCompany(state = Company.AUDIT_STATE_PASS)
    @RequestMapping("/purchase/detail/{enqid}")
    @RequirePurchase
    public String purchaseDetail(ModelMap model, @PathVariable("enqid") Integer enqid) {
        User user = ContextUtil.getUser();
        EnqEnquiry enquiry = enq.getEnqEnquiryByIdWidthItem(enqid);
        boolean hasPermission = hasPermission(enquiry);
        if (!hasPermission) {
            //无权访问
            return "redirect:/";
        }

        model.put("userid", user.getId());
        model.put("enquiry", enquiry);
        TemplateModel staticModel = FreemarkerUtils.getStaticModel(EnqPaymentEnum.class);
        model.put("EnqPaymentEnum", staticModel);

        return "enquiry/enquiry_purchase_detail";
    }

    private boolean hasPermission(EnqEnquiry enquiry) {
        User user = ContextUtil.getUser();
        boolean hasPermission = true;
        if (enquiry == null) {
            //乱输入的地址
            hasPermission = false;
        }

        //不是自己发的,要具体再判断
        if (hasPermission && (!user.getId().equals(enquiry.getUserId()))) {
            hasPermission = false;
            //判断是不是  管理员/财务
            List<UserEnum> userenum = new ArrayList<>();
            userenum.add(UserEnum.cadmin);
            userenum.add(UserEnum.cfinance);
            hasPermission = userService.getUserAuthorityByUserId(user.getId(), userenum);
            if (hasPermission) {
                Integer companyId = ContextUtil.getCompany().getId();
                Integer enqcompanyId = enquiry.getCustomerId();
                if (!companyId.equals(enqcompanyId)) {
                    hasPermission = false;
                    //还要再具体判断有没有权限看
                    List<Company> companies = companyService.allBranchCompany(companyId);
                    for (Company company : companies) {
                        Integer cid = company.getId();
                        if (cid.equals(enqcompanyId)) {
                            hasPermission = true;
                            break;
                        }
                    }
                } else {
                    hasPermission = true;
                }
            }
        }
        return hasPermission;
    }

    /**
     * 修改采购询价
     * Created by 张栋 on 2016/10/12 15:12
     * http://front.azt.com:8091/enquiry/purchase/editor/1040
     */
    @RequestMapping("/purchase/editor/{enqid}")
    public String companyInfo(ModelMap model, @PathVariable("enqid") Integer enqid, SessionStatus status) {
        status.setComplete();
        User user = ContextUtil.getUser();
        if (user == null) {
            return "redirect:/enquiry/purchase/create";
        }

        Company company = ContextUtil.getCompany();
        model.put("user", user);
        model.put("company", company);
        model.put("editor", true);

        EnqEnquiry enqmodel = enq.getEnqEnquiryByIdWidthItem(enqid, user.getId());

        if (enqmodel == null) {
            return "redirect:/enquiry/purchase/create";
        }

        String inviteCids = enqmodel.getInviteCids();
        if (StringUtils.isNotBlank(inviteCids)) {
            EnqRecommendChoose remommend = new EnqRecommendChoose();
            String[] cides = inviteCids.split(",");
            List<String> cidlist = Arrays.asList(cides);
            List<String> names = companyService.getCustommerNamesByIds(cidlist);
            remommend.setNames(names);
            remommend.setIds(cidlist);
            model.put("recod", remommend);
        }
        //生成字符串
        model.put("inviteCids", enqmodel.getInviteCids());
        model.put("inviteTels", enqmodel.getInviteTels());
        model.put("enqmodel", enqmodel);


        return "enquiry/enq_purchase_create";
    }


    @RequestMapping("/design/editor/{enqid}")
    public String designEditory(ModelMap model, @PathVariable("enqid") Integer enqid, SessionStatus status) {
        status.setComplete();
        User user = ContextUtil.getUser();
        if (user == null) {
            return "redirect:/enquiry/purchase/create";
        }

        Company company = ContextUtil.getCompany();
        model.put("user", user);
        model.put("company", company);
        model.put("editor", true);


        EnqEnquiry enqmodel = enq.getEnqEnquiryByIdWidthItem(enqid, user.getId());
        if (enqmodel == null) {
            return "redirect:/enquiry/purchase/create";
        }

        model.put("enqmodel", enqmodel);

        /*判断有无清单*/
        String excelpath = enqmodel.getExcelpath();
        List<EnqEnquiryItem> items = enqmodel.getItems();
        if (excelpath == null && (items == null || items.size() == 0)) {
            model.put("hasdetail", 0);
        } else {
            model.put("hasdetail", 1);
        }
        return "enquiry/enq_design_create";
    }

    /**
     * 项目详情,询价列表,查看报价
     * 报价详情-公开.html
     * Created by 张栋 on 2016/10/9 14:14
     * http://front.azt.com:8091/enquiry/purchase/quote/detail/994
     */
    @RequireCompany(state = Company.AUDIT_STATE_PASS)
    @RequirePurchase
    @RequestMapping("/purchase/quote/detail/{enqid}")
    public String purchaseQuoteDetail(ModelMap model, @PathVariable("enqid") Integer enqid) {
        EnqEnquiry enquiry = enq.getEnquiryById(enqid);
        List<EnqQuoteDetail> list = enq.getProjPurchaseQuoteDetail(enqid);
        List<EnqCatChoose> encats = enq.getEnqCatChoose(enqid);
        User user = ContextUtil.getUser();
        model.put("user", user);
        model.put("encats", encats);
        model.put("enq", enquiry);

        model.put("quotes", list);
        return "enquiry/enq_quote_purchase_detail";
    }

    /**
     * 项目详情,预算询价列表,查看报价
     * <p>
     * 询价下面对应的所有报价商
     * Created by 张栋 on 2016/10/9 14:14
     * http://front.azt.com:8091/enquiry/design/quote/detail/982
     */
    @RequireCompany(state = Company.AUDIT_STATE_PASS)
    @RequirePurchase
    @RequestMapping("/design/quote/detail/{enqid}")
    public String designQuoteDetail(ModelMap model, @PathVariable("enqid") Integer enqid) {
        EnqEnquiry enquiry = enq.getEnquiryById(enqid);
        boolean hasPermission = hasPermission(enquiry);
        if (!hasPermission) {
            //无权访问
            return "redirect:/";
        }
        User user = ContextUtil.getUser();
        model.put("user", user);
        List<EnqQuoteDetail> list = enq.getProjPurchaseQuoteDetail(enqid);
        List<EnqCatChoose> encats = enq.getEnqCatChoose(enqid);
        model.put("encats", encats);
        model.put("enq", enquiry);
        model.put("quotes", list);
        return "enquiry/enq_quote_design_detail";
    }

    /**
     * 采购报价清单
     * 报价清单-公开.html
     * Created by 张栋 on 2016/10/10 10:58
     */
    @RequireCompany(state = Company.AUDIT_STATE_PASS)
    @RequirePurchase
    @RequestMapping("/purchase/quote/detail/item/{quoteid}")
    public String purchaseQuoteDetailList(ModelMap model, @PathVariable("quoteid") Integer quoteid) {
        EnqQuote quote = enq.getEnqQuoteById(quoteid);
        EnqEnquiry enquiry = enq.getEnquiryById(quote.getEnquiryId());
        boolean hasPermission = hasPermission(enquiry);
        if (!hasPermission) {
            //无权访问
            return "redirect:/";
        }

        enq.saveWatchQuote(quote);//每次查看更新采购商查看时间
        User user = ContextUtil.getUser();
        model.put("userid", user.getId());

        //设置报价人
        Integer userId = quote.getUserId();
        User quoteuser = userService.getUserById(userId);
        model.put("quoteman", quoteuser.getRealName());

        List<EnqQuoteItemExt> list = enq.getEnqQuoteItemExt(quoteid);
        List<EnqCatChoose> encats = enq.getQuoteCatChoose(quoteid);
        model.put("encats", encats);
        model.put("quote", quote);
        model.put("enq", enquiry);
        model.put("items", list);
        return "enquiry/enq_quote_purchase_detail_item";
    }


    /**
     * 报价清单下载 多个以zip包,单个以文件
     * Created by 张栋 on 2016/10/17 13:37
     */
    @RequireCompany(state = Company.AUDIT_STATE_PASS)
    @RequireUser
    @RequestMapping("/quote/download/{quoteids}")
    public void companyInfo(ModelMap model, HttpServletRequest request, HttpServletResponse response, @PathVariable("quoteids") String quoteids) {
        String[] ids = quoteids.split(",");
        ServletOutputStream outputStream = null;
        String agent = request.getHeader("user-agent");
        //只有一个的时候,直接下载excel,多个的时候,打包下载zip
        if (ids.length == 1) {
            try {
                Workbook workbook = ext.getWorkbook(Integer.parseInt(ids[0]), null);
                ExcelUtil.initResponse(response, workbook.getSheetName(0), agent);
                outputStream = response.getOutputStream();
                workbook.write(outputStream);
                outputStream.flush();
                outputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        } else {
            try {
                response.setContentType("application/octet-stream");
                ExcelUtil.initResponse(response, "报价清单.zip", agent);
                outputStream = response.getOutputStream();
                ZipOutputStream zipout = new ZipOutputStream(outputStream);
                for (String idstr : ids) {
                    Integer quoteid = Integer.parseInt(idstr);
                    ext.getWorkbook(quoteid, zipout);
                }
                zipout.flush();
                zipout.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }


    /**
     * 设计报价清单
     * Created by 张栋 on 2016/10/10 10:58
     */
    @RequireCompany(state = Company.AUDIT_STATE_PASS)
    @RequirePurchase
    @RequestMapping("/design/quote/detail/item/{quoteid}")
    public String designQuoteDetailList(ModelMap model, @PathVariable("quoteid") Integer quoteid) {
        EnqQuote quote = enq.getEnqQuoteById(quoteid);
        enq.saveWatchQuote(quote);//每次查看更新采购商查看时间
        EnqEnquiry enquiry = enq.getEnquiryById(quote.getEnquiryId());
        boolean hasPermission = hasPermission(enquiry);
        if (!hasPermission) {
            //无权访问
            return "redirect:/";
        }

        User user = ContextUtil.getUser();
        model.put("userid", user.getId());
        User u = userService.getUserById(quote.getUserId());
        model.put("quoteman", u.getRealName());

        List<EnqQuoteItemExt> list = enq.getEnqQuoteItemExt(quoteid);
        List<EnqCatChoose> encats = enq.getQuoteCatChoose(quoteid);
        model.put("encats", encats);
        model.put("quote", quote);
        model.put("enq", enquiry);
        model.put("items", list);
        return "enquiry/enq_quote_design_detail_item";
    }


    /**
     * 我的项目详情-预算列表-预算详情
     *
     * @param budgetid 预算id
     * @param qtype    '1.设计需求 2.采购询价',
     *                 Created by 张栋 on 2016/9/20 13:23
     *                 http://front.azt.com:8091/enquiry/budget/detail/1/t/2
     */
    @RequireCompany(state = Company.AUDIT_STATE_PASS)
    @RequirePurchase
    @RequestMapping("/budget/detail/{budgetid}/t/{qtype}")
    public String budgetDetail(ModelMap model, @PathVariable("budgetid") Integer budgetid, @PathVariable("qtype") Integer qtype) {
        User user = ContextUtil.getUser();
        Integer companyId = user.getCompanyId();

        EnqBudgetDetailWrap wrap = enq.getBudGetDetailWrap(budgetid);
        //判断权限
        //是不是自己公司的,是自己公司的没问题
        EnqBudget enqBudget = wrap.getEnqBudget();
        Integer customerId = enqBudget.getCustomerId();
        if (!companyId.equals(customerId)) {
            //不是自己公司的,则要判断该人物是不是管理人员或者财务
            List<UserEnum> userenum = new ArrayList<>();
            userenum.add(UserEnum.cadmin);
            userenum.add(UserEnum.cfinance);
            boolean hasPermission = userService.getUserAuthorityByUserId(user.getId(), userenum);
            if (hasPermission) {
                hasPermission = false;
                //是的,有权限,此时要判断是不是自己子公司的
                List<Company> companies = companyService.allBranchCompany(companyId);
                for (Company company : companies) {
                    Integer cid = company.getId();
                    if (cid.equals(customerId)) {
                        hasPermission = true;
                        break;
                    }
                }
            }
            if (!hasPermission) {
                return "redirect:/";
            }
        }

        model.put("budgets", wrap);
        model.put("budgetid", budgetid);
        model.put("userid", user.getId());
        model.put("EnqPaymentEnum", FreemarkerUtils.getStaticModel(EnqPaymentEnum.class));
        model.put("qtype", qtype);

        if (qtype == 1) {
            return "enquiry/enq_budget_design_detail";
        } else {
            return "enquiry/enq_budget_purchase_detail";
        }
    }

    /**
     * 下载完整预算清单
     * Created by 张栋 on 2016/10/20 10:38
     */
    @RequireCompany(state = Company.AUDIT_STATE_PASS)
    @RequireUser
    @RequestMapping("/budget/detail/download/{budgetid}")
    public void budgetDetailDownload(ModelMap model, HttpServletResponse response, @PathVariable Integer budgetid) {
        EnqBudgetDetailWrap wrap = enq.getBudGetDetailWrap(budgetid);
        List<EnqQuoteItemExt> detailList = wrap.getDetailList();
        ServletOutputStream outputStream = null;
        try {
            Workbook workbook = ext.getBgetWorkBbook(detailList);
            ExcelUtil.initResponse(response, "预算清单", null);
            outputStream = response.getOutputStream();
            workbook.write(outputStream);
            outputStream.flush();
            outputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 制作预算成本清单  part1
     * 根据选择的至少两家公司的报价
     * 主列表
     * <p>
     * enqid 询价id
     * Created by 张栋 on 2016/9/20 14:54
     * http://front.azt.com:8091/enquiry/budget/design/create/2909,2910
     */
    @RequireCompany(state = Company.AUDIT_STATE_PASS)
    @RequirePurchase
    @RequestMapping("/budget/design/create/{enqid}/{quoteids}")
    public String budgetCreateDesign(ModelMap model, @PathVariable("quoteids") String quoteids, @PathVariable("enqid") Integer enqid) {
        String[] qids = quoteids.split(",");
        List<Integer> ids = new ArrayList<>();
        for (String qid : qids) {
            ids.add(Integer.parseInt(qid));
        }
        List<EnqBgetCreate> list = enq.getEnqBgetCreate(ids);
        model.put("enqid", enqid);
        model.put("createList", list);
        return "enquiry/enq_budget_design_create";
    }


    /**
     * 制作预算成本清单-查看清单 part2
     * load出查看清单
     *
     * @param quoteid 预算列表每一列的详情,报价主表id
     *                Created by 张栋 on 2016/9/21 10:15
     */
    @RequireCompany(state = Company.AUDIT_STATE_PASS)
    @RequirePurchase
    @RequestMapping("/budget/design/create/quote/{quoteid}")
    public String budgetCreateDesignQuoteItem(ModelMap model, @PathVariable("quoteid") Integer quoteid) {
        List<EnqQuoteItemExt> budgetDetails = enq.getBudGetDetail(quoteid);
        model.put("quoteid", quoteid);
        model.put("detailList", budgetDetails);
        return "enquiry/enq_budget_design_create_item";
    }

    /**
     * 制作预算成本清单  part3
     * 生成预算成本清单
     *
     * @param quoteid 选择的报价id
     *                Created by 张栋 on 2016/9/21 10:33
     */
    @RequireCompany(state = Company.AUDIT_STATE_PASS)
    @RequirePurchase
    @RequestMapping(value = "/budget/design/create/save", method = RequestMethod.POST)
    @ResponseBody
    public AjaxJson budgetCreateDesignSave(Integer quoteid) {
        AjaxJson j = AjaxJson.success();
        User user = ContextUtil.getUser();
        Integer userid = user.getId();
        Integer companyId = user.getCompanyId();
        Integer budgetid = enq.budgetDesignSave(quoteid, userid, companyId);
        j.setObj(budgetid);
        return j;
    }


    /**
     * 制作采购成本清单  part1
     * 主列表
     * enqid 询价id
     * Created by 张栋 on 2016/9/20 14:54
     * http://front.azt.com:8091/enquiry/budget/purchase/create/2916,2914
     */
    @RequireCompany(state = Company.AUDIT_STATE_PASS)
    @RequirePurchase
    @RequestMapping("/budget/purchase/create/{enqid}/{quoteids}")
    public String budgetCreatePurchase(ModelMap model, @PathVariable("enqid") Integer enqid, @PathVariable("quoteids") String quoteids) {
        String[] qids = quoteids.split(",");
        List<Integer> ids = new ArrayList<>();
        for (String qid : qids) {
            ids.add(Integer.parseInt(qid));
        }
        //2016,12,29 胡子强,  前面转预算,只能自己转了,所以这里要验证是不是自己的
        User user = ContextUtil.getUser();
        EnqEnquiry enquiry = enq.getEnquiryById(enqid);
        boolean haspermission = false;

        if (enquiry.getUserId().equals(user.getId())) {
            haspermission = true;
        }

        if (!haspermission) {
            return "redirect:/";
        }

        List<EnqBgetPurchaseCreate> list = this.enq.getEnqBgetPchurCreate(enqid, ids);
        model.put("createList", list);
        model.put("enqid", list.size() > 0 ? list.get(0).getEnquiryId().toString() : "");
        return "enquiry/enq_budget_purchase_create";
    }


    /**
     * 保存生成采购成本清单   part2
     * Created by 张栋 on 2016/9/27 16:46
     */
    @RequireCompany(state = Company.AUDIT_STATE_PASS)
    @RequirePurchase
    @RequestMapping("/budget/purchase/create/save")
    @ResponseBody
    public AjaxJson budgetPurchaseSave(@RequestBody EnqBgetPchaseSaveWrap checked) {
        AjaxJson j = new AjaxJson();
        User user = ContextUtil.getUser();
        Integer companyId = user.getCompanyId();
        EnqBudget enqBudget = enq.budgetPurchaseSave(checked.getEnqid(), checked.getChecked(), user.getId(), companyId);
        if (enqBudget == null) {
            j.setSuccess(false);
            j.setMsg("生成失败");
        }
        j.setObj(enqBudget.getId());
        return j;
    }


    /**
     * 预算转采购
     * Created by 张栋 on 2016/10/25 14:25
     */
    @RequireCompany(state = Company.AUDIT_STATE_PASS)
    @RequirePurchase
    @RequestMapping("/budget/to/purchase")
    @ResponseBody
    public AjaxJson budgetTopurchase(Integer budgetid, String deadtime, ModelMap model) {
        AjaxJson j = new AjaxJson();
        User user = ContextUtil.getUser();

        Integer userId = user.getId();
        Integer companyId = user.getCompanyId();

        try {
            EnqEnquiry enquiry = enq.budgetTopurchase(budgetid, deadtime, userId, companyId);
            model.put("enqmodel", enquiry);
            j.setObj(enquiry.getProjectId());
        } catch (Exception e) {
            j.setSuccess(false);
            j.setMsg("转发失败");
            e.printStackTrace();
        }
        return j;
    }

    @RequestMapping({"/design/choose"})
    public String designChooes2(ModelMap model) {
        return "forward:/enquiry/design/choose/0";
    }

    /**
     * 预算询价,选择创建类型
     * Created by 张栋 on 2016/9/21 13:28
     */
    @RequestMapping({"/design/choose/{projectId}"})
    public String designChooes(ModelMap model, @PathVariable("projectId") Integer projectId) {
        if (projectId == null || projectId == 0) {
            model.put("projectId", null);
        }
        return "enquiry/enq_choose_design";
    }


    @RequestMapping({"/purchase/choose"})
    public String purchaseChooes2(ModelMap model) {
        return "forward:/enquiry/purchase/choose/0";
    }

    /**
     * 采购询价,选择创建类型
     * Created by 张栋 on 2016/9/21 13:28
     */
    @RequestMapping({"/purchase/choose/{projectId}"})
    public String purchaseChooes(ModelMap model, @PathVariable("projectId") Integer projectId) {
        if (projectId == null || projectId == 0) {
            model.put("projectId", null);
        }
        return "enquiry/enq_choose_purchase";
    }

    /**
     * 设计/采购  选择
     * Created by 张栋 on 2016/9/21 16:14
     */
    @RequestMapping("/all/choose")
    public String purchaseDesignChooes(ModelMap model) {
        return "enquiry/enq_choose_all";
    }


    /**
     * 公开询价
     * Created by 张栋 on 2017/2/15 16:48
     */
    @RequestMapping({"/purchase/public"})
    public String purchasePublic(ModelMap model, HttpServletRequest request, SessionStatus status) {
        model.put("recod", new EnqRecommendChoose());
        return "forward:/enquiry/purchase/create/0";

    }

    @RequestMapping({"/purchase/public/{projectId}"})
    public String purchasePublic2(@PathVariable Integer projectId, ModelMap model, HttpServletRequest request, SessionStatus status) {
        model.put("recod", new EnqRecommendChoose());
        return "forward:/enquiry/purchase/create/" + projectId;
    }

    /**
     * 未登录的创建采购询价
     * Created by 张栋 on 2016/9/21 16:21
     */
    @RequestMapping({"/purchase/create/{projectId}"})
    public String purchaseCreate(@PathVariable Integer projectId, ModelMap model, HttpServletRequest request, SessionStatus status) {
        User user = ContextUtil.getUser();
        model.put("user", user);

        Company company = ContextUtil.getCompany();
        model.put("company", company);
        if (projectId == null || projectId == 0) {
            model.put("projectId", null);
        } else {
            if (user == null) {
                model.put("projectId", null);
            }
        }
        //选择的推荐供应商处理
        Object recod = model.get("recod");
        EnqRecommendChoose recommend = (EnqRecommendChoose) recod;
        if (recommend != null && recommend.getIds() != null) {
            List<String> typess = recommend.getTypess();
            StringBuffer inviteCids = new StringBuffer();
            StringBuffer inviteTels = new StringBuffer();
            boolean cidsfirst = true;
            boolean telsfirst = true;
            for (int i = 0; i < typess.size(); i++) {
                String type = typess.get(i);
                if (type.equals("1")) {//公司
                    if (!cidsfirst) {
                        inviteCids.append(",");
                    } else {
                        cidsfirst = false;
                    }
                    inviteCids.append(recommend.getIds().get(i));
                } else {
                    if (!telsfirst) {
                        inviteTels.append(",");
                    } else {
                        telsfirst = false;
                    }
                    inviteTels.append(recommend.getIds().get(i));
                }
            }

            //生成字符串
            model.put("inviteCids", inviteCids);
            model.put("inviteTels", inviteTels);
        }

        if (company != null) {
            //已经有的项目列表
            List<EnqProject> projects = enq.getProjeListBYUserid(user.getId());
            model.put("projects", projects);
        }
        return "enquiry/enq_purchase_create";
    }


    @RequestMapping("/purchase/create/choosecompany")
    public String choosecompany2(ModelMap model, SessionStatus status) {
        return "forward:/enquiry/purchase/create/choosecompany/0";
    }

    /**
     * 登录后的发布---不公开发布,,先选择供应商
     * 发布采购询价-不公开.html
     * Created by 张栋 on 2016/10/10 13:11
     */
    @RequireCompany(state = Company.AUDIT_STATE_PASS)
    @RequestMapping("/purchase/create/choosecompany/{projectId}")
    @RequirePurchase
    public String choosecompany(@PathVariable Integer projectId, ModelMap model, SessionStatus status) {
        if (projectId == null || projectId == 0) {
            model.put("projectId", null);
        }
//        status.setComplete();
        //获取推荐供应商,
        Integer companyid = ContextUtil.getUser().getCompanyId();
        List<EnqPurchaseRecommend> recommends = enq.getEnqRecommend(companyid);
        model.put("recommends", recommends);

        Set<EnqPurchaseRecommend> recommendSet = new HashSet<>(recommends);
        model.put("recommendset", recommendSet);
        return "enquiry/enq_purchase_create_choosecompany";
    }

    /**
     * 创建预算询价
     *
     * @param detailed 有无清单,1有,0没有
     *                 Created by 张栋 on 2016/10/14 13:46
     */
    @RequestMapping({"/design/create/{detailed}"})
    public String designCreateDetailed2(ModelMap model, @PathVariable Integer detailed) {
        return "forward:/enquiry/design/create/" + detailed + "/0";
    }

    /**
     * 创建预算询价   有无清单
     *
     * @param detailed 有无清单,1有,0没有
     *                 Created by 张栋 on 2016/10/14 13:46
     */
    @RequestMapping({"/design/create/{detailed}/{projectId}"})
    public String designCreateDetailed(ModelMap model, @PathVariable("detailed") Integer detailed, @PathVariable("projectId") Integer projectId) {

        User user = ContextUtil.getUser();
        Company company = ContextUtil.getCompany();
        model.put("company", company);
        model.put("user", user);
        if (projectId == null || projectId == 0) {
            model.put("projectId", null);
        }
        if (company != null) {
            //已经有的项目列表
            List<EnqProject> projects = enq.getProjeListBYUserid(user.getId());
            model.put("projects", projects);
        }
        model.put("hasdetail", detailed);
        return "enquiry/enq_design_create";
    }

    /**
     * 选择供应商后提交数据
     * Created by 张栋 on 2016/10/11 11:03
     */
    @RequestMapping("/purchase/create/savechoose")
    @ResponseBody
    public AjaxJson createSaveChoose(@RequestBody EnqRecommendChoose choosed, ModelMap model) {
        AjaxJson j = new AjaxJson();
        j.setSuccess(true);
        model.put("recod", choosed);
        return j;
    }

    /**
     * 创建询价提交,采购询价,预算询价
     * Created by 张栋 on 2016/9/27 9:52
     */
    @RequestMapping("/purchase/create/save")
    @ResponseBody
    public AjaxJson purchaseSave(ModelMap model, EnqEnquiry enqa, SessionStatus status) {
        AjaxJson j = new AjaxJson();
        //是否是临时保存
        /**
         * 用户填写资料后,发现未登录,进行登录,刷新页面前保存临时数据
         */
        Boolean isTemp = RequestUtils.getBoolean("temporary", false);
        if (isTemp) {
            //保存临时对象至session
            String excelpath = enqa.getExcelpath();
            if (StringUtils.isNotBlank(excelpath)) {
                enqa.setItems(null);
            }

            model.put("enqmodel", enqa);
            j.setObj(true);

        } else {
            //判断登录情况
            User user = ContextUtil.getUser();
            if (user == null) {
                j.setSuccess(false);
                j.setMsg("请先登录");
                j.setCode(1);
                return j;
            } else {
                if (StrUtil.isBlank(user.getMobile())) {
                    j.setSuccess(false);
                    j.setMsg("请先绑定手机");
                    j.setCode(2);
                    return j;
                }
            }

            Company company = ContextUtil.getCompany();
            if (company == null) {
                j.setSuccess(false);
                j.setMsg("您还未绑定任何企业，无法发布询价单！");
                j.setObj("/user/companySearch");
                j.setCode(3);
                return j;
            }

            if (company.getIspurchaser() == null || company.getIspurchaser() != 1) {
                j.setSuccess(false);
                j.setMsg("只有认证过的采购商才能发布");
                j.setCode(4);
                return j;
            }

            if (company.getAuditState() != Company.AUDIT_STATE_PASS) {
                j.setSuccess(false);
                j.setMsg("您的企业资料尚未通过审核，无法发布询价单！");
                j.setObj("/company/info");
                j.setCode(5);
                return j;
            }

            //1.设计需求 2.采购询价
            Integer qtype = enqa.getQtype();
            boolean hasPermission = false;

            //验证权限,有没有发布的权限

            Role purchaseRole = ContextUtil.hasPurchaser();
            if (purchaseRole != null) {
                if (qtype == 1) {
                    hasPermission = userPermissionService.hasThisPerm(purchaseRole.getId(), new String[]{"DesignEnquiry"}, 2);
                } else {
                    hasPermission = userPermissionService.hasThisPerm(purchaseRole.getId(), new String[]{"PurchaseEnquiry"}, 2);
                }
            }

            if (!hasPermission) {
                j.setSuccess(false);
                j.setMsg("您没有发布权限");
                j.setCode(6);
                return j;
            }


            //保存之前的处理
            Integer userid = user.getId();
            Integer companyId = user.getCompanyId();
            enqa.setUserId(userid);
            enqa.setPhone(user.getMobile());
            enqa.setCustomerId(companyId);
            enqa.setPubdate(new Date());
            enqa.setOrignexcel(enqa.getExcelpath());
            enqa.setRemoved(0);
            enqa.setHadsendsms(0);
            EnqEnquiry enqEnquiry = enq.savePurchaseExternal(enqa);

            status.setComplete();
            j.setMsg(enqEnquiry.getId() + "-" + enqEnquiry.getProjectId());
        }

        return j;
    }

    /**
     * 创建设计需求
     * Created by 张栋 on 2016/10/14 14:42
     */
    @RequestMapping("/design/create/save")
    @ResponseBody
    public AjaxJson designSave(ModelMap model, EnqEnquiry enqa, SessionStatus status) {
        AjaxJson j = new AjaxJson();
        //是否是临时保存
        /**
         * 用户填写资料后,发现未登录,进行登录,刷新页面前保存临时数据
         */
        Boolean isTemp = RequestUtils.getBoolean("temporary", false);
        if (isTemp) {
            //保存临时对象至session
            model.put("enqmodel", enqa);
            j.setObj(true);
        } else {
            status.setComplete();
            //保存至数据库
            enqa.setQtype(1);
            enqa.setPubdate(new Date());
            enq.savePurchaseExternal(enqa);
        }

        return j;
    }

    /*
    *
    *供应商平台推送列表页面
    *
    * */
    @RequireProvider
    @RequestMapping(value = "/pushEnquiry_{qtype}/list")
    public String pushEnquiryList(HttpServletRequest request, HttpServletResponse response, ModelMap model, PushEnqirySearchDto psd, @PathVariable("qtype") Integer qtype, Integer pageNo, String tipsMsg) throws Exception {

        User user = ContextUtil.getUser();
        Integer companyId = user.getCompanyId();
        Integer userId = user.getId();
        psd.setUserId(userId);
        psd.setCompanyId(companyId);
        psd.setQtype(qtype);
        TPagination<PushEnquiryListDto> pushEnquiryListDesgin = enq.getPushEnquiryList(psd, pageNo == null ? 1 : pageNo, PAGESIZE);

        Map<String, Object> searchMap = BeanUtils.copyBean2Map(psd);
        pushEnquiryListDesgin.setParams(searchMap);

        model.put("desginList", pushEnquiryListDesgin);
        if (StrUtil.isNotBlank(tipsMsg)) {
            model.put("tipsMsg", URLDecoder.decode(tipsMsg, "UTF-8"));
        }
        model.put("qtype", qtype);
        //model.put("purchaseList" , pushEnquiryListPurchase);
        model.put("psd", psd);

        model.put("myStringUtils", FreemarkerUtils.getStaticModel(MyStringUtils.class));

        return "enquiry/push_enquiry_list";

    }


    @RequireProvider
    @RequestMapping(value = "/quote_{qtype}/list")
    public String quoteList(HttpServletRequest request, HttpServletResponse response, ModelMap model, PushEnqirySearchDto psd, @PathVariable("qtype") Integer qtype, Integer pageNo) {

        User user = ContextUtil.getUser();
        Integer companyId = user.getCompanyId();
        Integer userId = user.getId();
        psd.setUserId(userId);
        psd.setCompanyId(companyId);
        psd.setQtype(qtype);
        TPagination<QuoteListDto> pushEnquiryListDesgin = enq.getMyQuoteList(psd, pageNo == null ? 1 : pageNo, PAGESIZE);

        Map<String, Object> searchMap = BeanUtils.copyBean2Map(psd);
        pushEnquiryListDesgin.setParams(searchMap);

//        TemplateModel staticModel = FreemarkerUtils.getStaticModel(EnqQuoteEnum.class);
//        model.put("EnqQuoteEnum", staticModel);

        // 报价状态
        Map<String, String> allQuoteStat = EnqQuoteEnum.getAllQuoteStat();
        model.put("allQuoteStat", allQuoteStat);

        model.put("desginList", pushEnquiryListDesgin);
        model.put("qtype", qtype);
        model.put("psd", psd);

        model.put("myStringUtils" , FreemarkerUtils.getStaticModel(MyStringUtils.class));

        return "enquiry/quote_list";

    }

    @RequireProvider
    @RequestMapping(value = "/quoteCancle")
    @ResponseBody
    public AjaxJson quoteCancle(Integer quoteId) {
        if (quoteId != null) {
            EnqQuote quote = eqs.getQuoteById(quoteId);
            if (quote.getState().compareTo(EnqQuoteEnum.QUT_POSTED.getIndex()) == 0) {
                quote.setState(EnqQuoteEnum.QUT_CLOSE.getIndex());
                eqs.saveOrUpdateQuote(quote);
                return AjaxJson.success();
            }
        }
        return AjaxJson.error("取消失败");
    }


    /**
     * 供应商报价页面
     *
     * @param request
     * @param response
     * @param model
     * @param enquiryId
     * @return
     */
    @RequireProvider
    @RequestMapping(value = "/quote")
    public String quote(HttpServletRequest request, HttpServletResponse response, ModelMap model, Integer enquiryId) throws Exception {

        QuoteEnquiryDto enquiry = enq.getQuoteInfo(enquiryId, ContextUtil.getCompany().getId());

        if (enquiry == null) {
            model.put("tipsMsg", URLEncoder.encode("抱歉，您无法对此询价进行报价，请从列表中选择", "UTF-8"));
            return "redirect:/enquiry/pushEnquiry_2/list";
        }

        model.put("enquiry", enquiry);

        User timeUser = userService.getUserById(ContextUtil.getUserId());
        model.put("needDown", enquiry.getDownListCus() == null ? true : (enquiry.getDownListCus().indexOf("," + timeUser.getCompanyId() + ",") > -1 ? false : true));
        Integer canQuote = 1;//是否可以报价，1可以，0不可以，当报价的而用户没有真实姓名或者手机号时 不能报价
        if (StrUtil.isBlank(timeUser.getRealName()) || StringUtils.isBlank(timeUser.getMobile())) {//当这个用户没有设置真实姓名和手机时，不能进行报价
            canQuote = 0;
        }
        model.put("canQuote", canQuote);

        if (StrUtil.isNotBlank(enquiry.getBatchPay())) {
            JSONArray objects = com.alibaba.fastjson.JSONObject.parseArray(enquiry.getBatchPay());
            model.put("batchPay", objects);
        }

        model.put("myStringUtils", FreemarkerUtils.getStaticModel(MyStringUtils.class));


        return "enquiry/quote";
    }


    @RequireProvider
    @RequestMapping(value = "/quoteEdit")
    public String quoteEdit(ModelMap model, Integer quoteId) {
        EnqQuote quote = eqs.getCanEditQuoteById(quoteId);
        if (quote != null && quote.getUserId().compareTo(ContextUtil.getUserId()) == 0 && quote.getCompanyId().compareTo(ContextUtil.getCompany().getId()) == 0) {
            //为了测试方便  换一只判断   记得一定要换回上面的  很重要
            //if(quote != null){
            QuoteEnquiryDto enquiry = enq.getBaseEnquiryInfo(quote.getEnquiryId());
            String[] afArray = quote.getAttachfile() == null ? null : quote.getAttachfile().split(";");
            List<EnqQuoteItem> quoteItem = eqs.getItemByQuote(quoteId);
            model.put("afArray", afArray);
            model.put("enquiry", enquiry);
            if (StrUtil.isNotBlank(enquiry.getBatchPay())) {
                JSONArray objects = com.alibaba.fastjson.JSONObject.parseArray(enquiry.getBatchPay());
                model.put("batchPay", objects);
            }

            model.put("quoteItem", quoteItem);
            model.put("quote", quote);
            model.put("myStringUtils", FreemarkerUtils.getStaticModel(MyStringUtils.class));
            return "enquiry/quote_edit";
        } else {
            return "forward:/enquiry/quote_2/list";
        }
    }

    @RequireProvider
    @RequestMapping(value = "/quoteShow")
    public String quoteShow(ModelMap model, Integer quoteId) {
        EnqQuote quote = eqs.getQuoteById(quoteId);
        if (quote != null && quote.getUserId().compareTo(ContextUtil.getUserId()) == 0 && quote.getCompanyId().compareTo(ContextUtil.getCompany().getId()) == 0) {
            QuoteEnquiryDto enquiry = enq.getBaseEnquiryInfo(quote.getEnquiryId());
            String[] afArray = quote.getAttachfile() == null ? null : quote.getAttachfile().split(";");
            List<EnqQuoteItem> quoteItem = eqs.getItemByQuote(quoteId);
            model.put("afArray", afArray);
            model.put("enquiry", enquiry);
            if (StrUtil.isNotBlank(enquiry.getBatchPay())) {
                JSONArray objects = com.alibaba.fastjson.JSONObject.parseArray(enquiry.getBatchPay());
                model.put("batchPay", objects);
            }

            model.put("quoteItem", quoteItem);
            model.put("quote", quote);
            model.put("myStringUtils", FreemarkerUtils.getStaticModel(MyStringUtils.class));
        }
        return "enquiry/quote_show";
    }


    /**
     * 保存报价功能
     *
     * @param request
     * @param response
     * @param model
     * @param quote
     * @param editType  1 重新上传  2 删除清单item
     * @param editSpace 1 上传资料  2清单列表
     * @return
     */
    @RequestMapping(value = "/saveQuote")
    @ResponseBody
    @RequireProvider
    public AjaxJson saveQuote(HttpServletRequest request, HttpServletResponse response, ModelMap model, EnqQuote quote, Integer editType, Integer editSpace, Integer[] itemids, Integer canQuote , Integer qtype , Double listtotalPrice) {

        try {
            if (canQuote != null && canQuote.compareTo(1) == 0) {
                if (quote.getId() == null) {
                    User user = ContextUtil.getUser();
                    if (qtype == 1) {
                        quote.setState(EnqQuoteEnum.QUT_STAY.getIndex());
                    } else {
                        if (quote.getItem() == null || quote.getItem().size() == 0 || listtotalPrice == null || !(listtotalPrice.compareTo(0d) > 0)) {
                            return AjaxJson.error("未分析出有效报价清单");
                        } else {
                            quote.setState(EnqQuoteEnum.QUT_POSTED.getIndex());
                            quote.setTotalPrice(listtotalPrice);
                        }
                    }
                    quote.setUserId(user.getId());
                    quote.setQuoteDate(new Date());
                    quote.setCompanyId(user.getCompanyId());
                    quote.setCreatetime(new Date());
                    quote.setContacter(user.getRealName());
                    quote.setPhone(user.getMobile());
                    quote.setFirstpass(Company.FISRT_PASS);
                    eqs.saveOrUpdateQuote(quote);
                } else {
                    EnqQuote oldQuote = eqs.getCanEditQuoteById(quote.getId());
                    if (oldQuote == null) {
                        return AjaxJson.error("该报价已被纳入预算或已下单，不能进行修改");
                    }
                    if ((oldQuote.getAttachfile() == null && !";".equals(quote.getAttachfile())) || (oldQuote.getAttachfile() != null && !oldQuote.getAttachfile().equals(quote.getAttachfile())) && qtype == 1) {
                        oldQuote.setState(EnqQuoteEnum.QUT_STAY.getIndex());
                    }
                    oldQuote.setAttachfile(quote.getAttachfile());
                    oldQuote.setUpdatetime(new Date());
                    boolean delItems = false;
                    if (editType != null && editType == 1 && editSpace != null && editSpace == 1) {
                        oldQuote.setExcelName(quote.getExcelName());
                        oldQuote.setExcelpath(quote.getExcelpath());
//                        oldQuote.setState(EnqQuoteEnum.QUT_STAY.getIndex());
                        if (qtype == 1) {
                            oldQuote.setState(EnqQuoteEnum.QUT_STAY.getIndex());
                        } else {
                            if (quote.getItem() == null || quote.getItem().size() == 0 || listtotalPrice == null || !(listtotalPrice.compareTo(0d) > 0)) {
                                return AjaxJson.error("未分析出有效报价清单");
                            } else {
                                oldQuote.setState(EnqQuoteEnum.QUT_POSTED.getIndex());
                                oldQuote.setItem(quote.getItem());
                                oldQuote.setTotalPrice(listtotalPrice);
                            }
                        }
                        delItems = true;
                    }
                    List<Integer> iids = null;
                    if (editType != null && editType == 2 && editSpace != null && editSpace == 2 && itemids != null && itemids.length > 0) {
                        iids = Arrays.asList(itemids);
                        oldQuote.setTotalPrice(quote.getTotalPrice());
                    }
                    if (oldQuote.getState().compareTo(EnqQuoteEnum.QUT_REFUSE.getIndex()) == 0) {
                        if (qtype == 1) {
                            oldQuote.setState(EnqQuoteEnum.QUT_STAY.getIndex());
                        }else{
                            oldQuote.setState(EnqQuoteEnum.QUT_POSTED.getIndex());
                        }
                    }
                    oldQuote.setSuggest(null);//编辑之后删除审核意见
                    eqs.updateQuoteWithDelItem(oldQuote, iids, delItems);
                }
            } else {
                return AjaxJson.error("cantQuote");
            }
        } catch (Exception e) {
            return AjaxJson.error(e.getMessage());
        }

        return AjaxJson.success();
    }


    /**
     * 导出询价清单
     *
     * @param request
     * @param response
     * @param model
     * @param enquiryId
     */
    @RequestMapping(value = "/exportItem")
    @ResponseBody
    @RequireCompany
    public void exportEnquiryItem(HttpServletRequest request, HttpServletResponse response, ModelMap model, Integer enquiryId, Integer qtype) {
        if (enquiryId != null && qtype != null && ContextUtil.getUser().getCompanyId() != null) {
            enq.exportEnquiryItem(enquiryId, qtype, ContextUtil.getUser().getCompanyId(), response, request);
            enq.updateEnqDowsCus(ContextUtil.getUser().getCompanyId(), enquiryId);//保存下载记录
        }
    }


    /**
     * 报价分析功能
     * @param excelPath
     * @param excelName
     * @return
     */
    @RequestMapping("/analyzeQuote")
//    @ResponseBody
    public String analyzeQuote(ModelMap model , String excelPath , String excelName , Integer enquiryId , Integer projectId , Integer quoteId) {

        //try {
        Map<String, Object> result = enq.importQuoteItem(excelPath, excelName, enquiryId);
        result.put("projectId", projectId);
        result.put("quoteId", quoteId);
        //}

//        if((Boolean) result.get("success")){
//            AjaxJson success = AjaxJson.success();
//            result.put("enquiryId" , enquiryId);
//            result.put("projectId" , projectId);
//            success.setAttributes(result);
//        }else {
//        }

        model.addAttribute("result", result);




        return "enquiry/quoteList";



    }


    /**
     * 导出询价清单    固定的格式  平台内部使用  增加系统那一列
     *
     * @param request
     * @param response
     * @param model
     * @param enquiryId
     */
    @RequestMapping(value = "/exportItemForTest")
    @ResponseBody
    @RequireCompany
    public void exportEnquiryItemForTest(HttpServletRequest request, HttpServletResponse response, ModelMap model, Integer enquiryId, Integer qtype) {
        if (enquiryId != null && qtype != null && ContextUtil.getUser().getCompanyId() != null) {
            enq.exportEnquiryItemForTest(enquiryId, qtype, ContextUtil.getUser().getCompanyId(), response, request);
//            enq.updateEnqDowsCus(ContextUtil.getUser().getCompanyId() , enquiryId);//保存下载记录
        }
    }


    /**
     * 导入报价清单
     *
     * @param request
     * @param response
     * @param model
     * @param filePath
     * @param fileName
     */
    @RequestMapping(value = "/importItem")
    @ResponseBody
    @RequireUser
    public void importQuoteItem(HttpServletRequest request, HttpServletResponse response, ModelMap model, String filePath, String fileName) {

    }


    /**
     * 比价
     * Created by 张栋 on 2017/3/16 14:10
     */
    @RequestMapping("/reference")
    @ResponseBody
    public AjaxJson reference(String name) {
        AjaxJson j = new AjaxJson();
        Map price = quoteService.reference(name);
        if (price == null) {
            j.setSuccess(false);
        } else {
            j.setAttributes(price);
            j.setSuccess(true);
        }
        return j;
    }



    @RequestMapping("/before_mulity_retry")
    public String beforeMulityRetry( ModelMap model){
        String excelpath = RequestUtils.getString("excelpath");
        model.put("excelpath",excelpath);
        return "enquiry/analy/enquiry_before_analysis";

    }
    //前台解析
    /**
     * 分组分析
     * Created by 张栋 on 2017/3/30 15:23
     */
    @RequestMapping("/mulity_retry")
    public String mulityRetry(HttpServletRequest request, ModelMap model) {
        Integer type = 1;
        boolean isMulity =false;
        try {

            String excelpath = RequestUtils.getString("excelpath");
//            type = RequestUtils.getInteger("type");
            // 解析
            List<PurchaseModel> excelMulityWraps = analysisService.tryPurchaseMulity(excelpath, 0, 1);
            if(excelMulityWraps.size() >1 ){
                //CPModel 保存到session
                model.put("CPModel",excelMulityWraps);
                model.put("wrapsize",excelMulityWraps.size());
                isMulity=true;
            }else if(excelMulityWraps.size()==1){
                readyModel(model, excelMulityWraps.get(0));
            }

        } catch (Exception e) {
            e.printStackTrace();
        }


       if(isMulity){
            return "enquiry/analy/enquiry_analysis_mulity_model";
        }else{
            return "enquiry/analy/enquiry_analysis_model";
        }
    }



    /**
     * 多tab情况下的每一个tab请求
     * Created by 张栋 on 2017/3/30 15:24
     */
    @RequestMapping("/mulity_one")
    public String mulityOne( ModelMap model,Integer index,Integer enqid){
        List<PurchaseModel> excelMulityWraps  = (List<PurchaseModel>) model.get("CPModel");

        model.put("mulityAnalysis",true);
        PurchaseModel purchaseModel  =excelMulityWraps.get(index);
        readyModel(model, purchaseModel);
/*
        EnqEnquiry enquiry = enq.getEnquiryById(enqid);
        // 解析
        model.put("enquiry", enquiry);
*/

        return "enquiry/analy/enquiry_analysis_model";
    }

    /**
     * 装model
     * Created by 张栋 on 2017/3/30 15:26
     */
    private void readyModel(ModelMap model, PurchaseModel tryPurchase) {
        List<String> titles = tryPurchase.getTitles();
        model.put("titles", titles);
        List<Integer> titleindex = tryPurchase.getTitleindex();
        model.put("titleindex", titleindex);
        //是否完美匹配
        model.put("titlePerfect", tryPurchase.isTitlePerfect());
        //最长列
        model.put("maxlength", tryPurchase.getMaxlength());

        model.put("contents", tryPurchase.getContents());

        model.put("cellStats", tryPurchase.getCellStats());

        //没有被匹配的行
        model.put("nocontents", tryPurchase.getNocontents());

        model.put("contentPerfect", tryPurchase.isContentPerfect());

        model.put("shebeiindex", tryPurchase.getShebeiindex());

        model.put("md5secret", tryPurchase.getShebeiscret());

        //还要显示匹配到的系统的名称,这个麻烦,要查类别3的,并形成map
        Map<String, Category> categorysMap = proCategoryService.getCategorysMap();
        model.put("categorysMap", categorysMap);
    }


    @RequestMapping("/o_analy_saveitem")
    @ResponseBody
    public AjaxJson analySaveItem(HttpServletRequest request, @RequestBody EnqEnquiryItemForm item,ModelMap model){
        AjaxJson j = new AjaxJson();
        EnqEnquiry enqmodel = (EnqEnquiry) model.get("enqmodel");
        if(enqmodel==null){
            enqmodel = new EnqEnquiry();
        }
        List<EnqEnquiryItem> enqitems = item.getItem();

        for (EnqEnquiryItem enqitem : enqitems) {
            Integer categoryPId = enqitem.getCategoryPId();

            //如果sid为空,则去取

            Category  cat = CategoryConstants.categoryByid.get(categoryPId+"");
            Category p = cat.getProCategory().getProCategory();
            enqitem.setCategorySId(p.getId());
            enqitem.setCategorySName(p.getName());
        }




        enqmodel.setItems(item.getItem());
        model.put("enqmodel",enqmodel);
        String[] typenames =item.getTypenames();
        String[] oldtitles =item.getOldtitles();

        //保存数据到仓库
        analysisService.saveOrUpdateRepository(item.getItem());
        //保存标题
        analysisService.saveOrUpdateRepositoryTitles(typenames, oldtitles, 1);
    
        return j;
    }

}



